package com.borball.store.comp;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;

import com.borball.store.dao.CompositeDAO;
import com.borball.store.dao.MStoreLogDAO;
import com.borball.store.dao.MaterailStoreDAO;
import com.borball.store.dao.ProductOutCheckDAO;
import com.borball.store.dao.ProductOutDAO;
import com.borball.store.domain.Composite;
import com.borball.store.domain.MStoreLog;
import com.borball.store.domain.Material;
import com.borball.store.domain.MaterialStore;
import com.borball.store.domain.OutCheckStatus;
import com.borball.store.domain.ProductAmount;
import com.borball.store.domain.ProductOut;
import com.borball.store.domain.ProductOutCheck;
import com.borball.store.domain.UnitAmount;
import com.borball.store.domain.User;
import com.borball.store.util.MaterialUtils;
import com.borball.store.util.StoreChangeActions;
import com.borball.store.util.UserUtils;

import craky.component.CommonTableModel;
import craky.componentc.JCButton;
import craky.componentc.JCComboBox;
import craky.componentc.JCLabel;
import craky.componentc.JCMessageBox;
import craky.componentc.JCNumberField;
import craky.componentc.JCPopupMenu;
import craky.componentc.JCScrollTable;
import craky.componentc.JCScrollText;
import craky.componentc.JCTable;
import craky.componentc.JCTableHeader;
import craky.componentc.JCTextField;
import craky.keeper.EmptyComponent;
import craky.keeper.KeeperApp;
import craky.keeper.KeeperPane;
import craky.layout.LineLayout;

public class MaterialOutPane extends KeeperPane {

	private static final long serialVersionUID = 4098577503066953853L;

	private static final String CMD_INSERT = "Insert";

	private static final String CMD_MODIFY = "Modify";

	private static final String[] COLUMNS_NAME = { "流水", "经手人", "状态", "备注", "成品加工数量", "退换元件数量", "时间" };

	protected KeeperApp keeper;

	protected User currentUser;

	protected CommonTableModel<ProductOut> model;

	protected List<ProductOut> data;

	protected ProductOut currentData;

	protected Action insertAction, modifyAction, deleteAction, submitAction, cancelAction;

	protected JCTable table;

	protected JCPopupMenu popup;

	protected JComponent top, bottom, center;

	protected JComponent ecUser, ecMemo, ecStatus;
	protected JComponent[] ecProducts, ecPAmount, ecReturnMaterials, ecReturnMAmount;
	protected JCTextField[] cpProducts, cpReturnMaterials;
	protected JCNumberField[] cpProductsAmount, cpReturnMaterialsAmount;
	protected JCComboBox cpUser, cpStatus;
	protected JCScrollText cpMemo;
	
	private JCButton btnModify, btnDelete, btnInsert, btnSubmit, btnCancel;

	private boolean modifying;
	ProductOutDAO productOutDao = new ProductOutDAO();
	MaterailStoreDAO storeDAO = new MaterailStoreDAO();
	MStoreLogDAO mStoreLogDAO = new MStoreLogDAO();
	CompositeDAO compositeDAO = new CompositeDAO();
	ProductOutCheckDAO productOutCheckDAO = new ProductOutCheckDAO();

	private int selectedIndex;

	public MaterialOutPane(KeeperApp keeper) {
		this.keeper = keeper;
		this.currentUser = keeper.getCurrentUser();

		this.selectedIndex = -1;

		load();
		initActions();
		initUI();
//		resetTypes();
	}

	private void initActions() {
		insertAction = new AbstractAction("\u6DFB\u52A0") {
			private static final long serialVersionUID = 5056698643009336063L;

			public void actionPerformed(ActionEvent e) {
				insertOrModify(true);
			}
		};

		modifyAction = new AbstractAction("\u4FEE\u6539") {
			private static final long serialVersionUID = 8222836515926767063L;

			public void actionPerformed(ActionEvent e) {
				insertOrModify(false);
			}
		};

		deleteAction = new AbstractAction("\u5220\u9664") {
			private static final long serialVersionUID = -4608405524916997614L;

			public void actionPerformed(ActionEvent e) {
				delete();
			}
		};

		submitAction = new AbstractAction("\u786E\u5B9A") {
			private static final long serialVersionUID = 6989199497316998154L;

			public void actionPerformed(ActionEvent e) {
				submit();
			}
		};

		cancelAction = new AbstractAction("\u53D6\u6D88") {
			private static final long serialVersionUID = 6989199497316998154L;

			public void actionPerformed(ActionEvent e) {
				cancel();
			}
		};

		modifyAction.setEnabled(false);
		deleteAction.setEnabled(false);
	}

	private void initUI() {
		btnModify = new JCButton(modifyAction);
		btnDelete = new JCButton(deleteAction);
		btnInsert = new JCButton(insertAction);
		btnSubmit = new JCButton(submitAction);
		btnCancel = new JCButton(cancelAction);
		btnModify.setPreferredSize(new Dimension(-1, 21));
		btnDelete.setPreferredSize(btnModify.getPreferredSize());
		btnInsert.setPreferredSize(btnModify.getPreferredSize());
		btnSubmit.setPreferredSize(btnModify.getPreferredSize());
		btnCancel.setPreferredSize(btnModify.getPreferredSize());
		btnSubmit.setVisible(false);
		btnCancel.setVisible(false);
		EmptyComponent centerParent = new EmptyComponent();
		setLayout(new BorderLayout());
		centerParent.setLayout(new BorderLayout(0, 3));
		createCenter();
		createBottom();

		this.add(centerParent, BorderLayout.CENTER);

		if (center != null) {
			centerParent.add(center, BorderLayout.CENTER);
		}

		if (top != null) {
			centerParent.add(top, BorderLayout.NORTH);
		}

		if (bottom != null) {
			centerParent.add(bottom, BorderLayout.SOUTH);
		}

		loadUsers();
		loadStatus();
	}

	private void loadStatus() {
	
		cpStatus.removeAllItems();
		cpStatus.addItem("新建");
		cpStatus.addItem("元件已发放");
//		cpStatus.addItem("结束");
		
		cpStatus.setSelectedIndex(-1);
		
	}
	
	private void loadUsers() {
		List<User> users = UserUtils.getInstance().getAllUsers();
	
		cpUser.removeAllItems();
		for (User user : users) {
			cpUser.addItem(user.getName());
		}
		cpUser.setSelectedItem(keeper.getCurrentUser());
		
	}

	public void load() {
		data = productOutDao.findAll();
		
		keeper.refreshStatus();
	}
	
	public void reload(){
		load();
		keeper.refreshStatus();
		model.refreshUI();
	}

	protected JComponent createBottom() {

		bottom = new EmptyComponent();
		bottom.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(new Color(84, 165, 213))));
		bottom.setPreferredSize(new Dimension(-1, 180));
		bottom.setLayout(new BorderLayout());
		bottom.add(createDetailComponent(), BorderLayout.CENTER);

		EmptyComponent buttonContainer = new EmptyComponent();
		buttonContainer.setLayout(new LineLayout(3, 0, 5, 0, 3, LineLayout.TRAILING, LineLayout.TRAILING,
				LineLayout.VERTICAL));
		buttonContainer.setPreferredSize(new Dimension(85, -1));
		buttonContainer.add(btnSubmit, LineLayout.END_FILL);

		buttonContainer.add(btnDelete, LineLayout.END_FILL);
		buttonContainer.add(btnModify, LineLayout.END_FILL);

		buttonContainer.add(btnInsert, LineLayout.END_FILL);
		buttonContainer.add(btnCancel, LineLayout.END_FILL);
		bottom.add(buttonContainer, BorderLayout.EAST);

		return bottom;
	}

	protected JComponent createCenter() {
		final Class<?>[] columnsClass = { Integer.class, String.class, String.class, String.class, String.class, String.class, Timestamp.class };
		final String[] getMethodsName = { "getId", "getUser", "getStatus", "getMemo", "getProducts", "getReturnUnits", "getCreated" };
		final String[] setMethodsName = { "setId", "setUser", "setStatus", "setMemo", "setProducts", "setReturnUnits", "setCreated" };
		final int[] columnsPreferredWidth = { 10, 12, 10, 130, 150, 150, 100 };
		EmptyComponent ec = new EmptyComponent();
		JCScrollTable scTable = new JCScrollTable();
		table = scTable.getTable();
		model = new CommonTableModel<ProductOut>(table, COLUMNS_NAME, columnsClass, getMethodsName, setMethodsName, data);
		TableRowSorter<CommonTableModel<ProductOut>> sorter = new TableRowSorter<CommonTableModel<ProductOut>>(model);

		scTable.setAlpha(0.0f);
		scTable.setColumnControlEnabled(false);
		ec.setLayout(new BorderLayout());
		ec.add(scTable, BorderLayout.CENTER);
		table.setModel(model);
		table.setDragEnabled(false);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setRowSorter(sorter);
		table.setRendererOpaque(false);
		((JCTableHeader) table.getTableHeader()).setShowPopupMenu(false);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				whenSelectionChanged(e);
			}
		});
		table.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				select(e);
			}

			public void mouseReleased(MouseEvent e) {
				showPopupMenu(e);
			}
		});

		for (int i = 0; i < columnsPreferredWidth.length; i++) {
			table.getColumnModel().getColumn(i).setPreferredWidth(columnsPreferredWidth[i]);
		}

		return center = ec;
	}

	private JComponent createDetailComponent() {
		EmptyComponent ec = new EmptyComponent();
		EmptyComponent firstRow = new EmptyComponent();
		EmptyComponent secondRow = new EmptyComponent();
		EmptyComponent thirdRow = new EmptyComponent();

		JCLabel lbUser = new JCLabel("经手人");
		JCLabel lbStatus = new JCLabel("当前状态");
		JCLabel lbMemo = new JCLabel("备注");

		Border border = new EmptyBorder(0, 0, 0, 5);
		cpUser =  new JCComboBox();
		cpStatus = new JCComboBox();
		cpMemo = new JCScrollText();
		cpMemo.getEditor().setLineWrap(true);

		firstRow.setLayout(new BoxLayout(firstRow, BoxLayout.X_AXIS));
		firstRow.setPreferredSize(new Dimension(-1, 25));

		firstRow.add(ecUser = createTitledComponent(lbUser, cpUser, border, 3));
		firstRow.add(ecStatus = createTitledComponent(lbStatus, cpStatus, border, 3));
		firstRow.add(ecMemo = createTitledComponent(lbMemo, cpMemo, border, 3));
		
		secondRow.setLayout(new BoxLayout(secondRow, BoxLayout.X_AXIS));
		secondRow.setPreferredSize(new Dimension(-1, 25));

		createProductsPane(secondRow, border);
		
		thirdRow.setLayout(new BoxLayout(thirdRow, BoxLayout.X_AXIS));
		thirdRow.setPreferredSize(new Dimension(-1, 25));
		createReturnedMaterialPane(thirdRow, border);
		
		ec.setLayout(new GridLayout(6, 1, 5, 5));
		ec.setBorder(new EmptyBorder(3, 5, 2, 2));
		
		JCLabel lbBasic = new JCLabel("基       本       信       息:");
		JCLabel lbProduct = new JCLabel("请输入成品加工的数量:");
		JCLabel lbReturn = new JCLabel("请输入元件损坏退还数量:");

		ec.add(lbBasic);
		ec.add(firstRow);
		ec.add(lbProduct);
		ec.add(secondRow);
		ec.add(lbReturn);
		ec.add(thirdRow);
		
		ecUser.setPreferredSize(new Dimension(100, -1));
		ecStatus.setPreferredSize(new Dimension(35, -1));
		ecMemo.setPreferredSize(new Dimension(250, -1));

		resetTextStatus(false);
		
		return ec;
	}

	private void createReturnedMaterialPane(EmptyComponent thirdRow, Border border) {
		List<Material> allMaterials = MaterialUtils.getInstance().getAll();
//		cpReturnMaterials = new JCTextField[allMaterials.size()];
		cpReturnMaterialsAmount = new JCNumberField[allMaterials.size()];
//		ecReturnMaterials = new JComponent[allMaterials.size()];
		ecReturnMAmount = new JComponent[allMaterials.size()];
		
		int i = 0;
		for (Material m : allMaterials) {
			JCLabel lbMaterial = new JCLabel(m.getName()+":");
//			JCLabel lbAmount = new JCLabel("数量");

//			cpReturnMaterials[i] = new JCTextField();
//			cpReturnMaterials[i].setText(m.getName());
//			cpReturnMaterials[i].setEnabled(false);
			
			cpReturnMaterialsAmount[i] = new JCNumberField(0,0,100);;

//			thirdRow.add(ecReturnMaterials[i] = createTitledComponent(lbMaterial, cpReturnMaterials[i], border, 3));
			thirdRow.add(ecReturnMAmount[i] = createTitledComponent(lbMaterial, cpReturnMaterialsAmount[i], border, 3));
			
//			ecReturnMaterials[i].setPreferredSize(new Dimension(25, -1));
			ecReturnMAmount[i].setPreferredSize(new Dimension(10, -1));
			i++;
		}		
	}

	protected void createProductsPane(EmptyComponent secondRow, Border border) {
		CompositeDAO dao = new CompositeDAO();
		
		List<Composite> composites = dao.findAll();
//		cpProducts = new JCTextField[composites.size()];
		cpProductsAmount = new JCNumberField[composites.size()];
//		ecProducts = new JComponent[composites.size()];
		ecPAmount = new JComponent[composites.size()];
		
		int i = 0;
		for (Composite m : composites) {
			JCLabel lbProduct = new JCLabel(m.getName()+":");
//			JCLabel lbAmount = new JCLabel("数量");

//			cpProducts[i] = new JCTextField();
//			cpProducts[i].setText(m.getName());
//			cpProducts[i].setEnabled(false);
			
			cpProductsAmount[i] = new JCNumberField(0,0,100);;

//			secondRow.add(ecProducts[i] = createTitledComponent(lbProduct, cpProducts[i], border, 3));
			secondRow.add(ecPAmount[i] = createTitledComponent(lbProduct, cpProductsAmount[i], border, 3));
			
//			ecProducts[i].setPreferredSize(new Dimension(25, -1));
			ecPAmount[i].setPreferredSize(new Dimension(10, -1));
			i++;
		}
	}

	private JComponent createTitledComponent(JComponent titleComponent, JComponent component, Border border, int hgap) {
		EmptyComponent ec = new EmptyComponent();
		ec.setBorder(border);
		ec.setLayout(new BorderLayout(hgap, 0));
		ec.add(component, BorderLayout.CENTER);

		if (titleComponent != null) {
			ec.add(titleComponent, BorderLayout.WEST);
		}

		return ec;
	}

	private void resetDetailValues() {
		if (bottom.isVisible()) {
			if (currentData == null) {
				clearValues();
			} else {
				fillValues();
			}

			resetTextStatus(false);
			resetButtonStatus(false);
			if("元件已发放".equals(cpStatus.getSelectedItem())){
				btnSubmit.setVisible(false);
				btnCancel.setVisible(false);
				btnInsert.setVisible(true);
				btnModify.setVisible(false);
				btnDelete.setVisible(false);
			}
			if("新建".equals(cpStatus.getSelectedItem())){
				btnSubmit.setVisible(false);
				btnCancel.setVisible(false);
				btnInsert.setVisible(true);
				btnModify.setVisible(true);
				btnDelete.setVisible(true);
			}
		}
	}

	private void clearValues() {
		 cpUser.setSelectedIndex(-1);
		 cpStatus.setSelectedIndex(-1);
		 cpMemo.getEditor().setText(null);

		 for (JCNumberField amount : cpProductsAmount) {
			 amount.setText(null);
		 }
		 
		 for (JCNumberField amount : cpReturnMaterialsAmount) {
			 amount.setText(null);
		 }
	}

	private void fillValues() {
		cpUser.setSelectedItem(currentData.getUser());
		cpStatus.setSelectedItem(currentData.getStatus());
		cpMemo.getEditor().setText(currentData.getMemo());
		
		UnitAmount[] uas = currentData.string2UnitAmount();
		int i =0;
		for (UnitAmount unitAmount : uas) {
			
//			cpProducts[i].setText(unitAmount.getName());
			cpReturnMaterialsAmount[i].setText(String.valueOf(unitAmount.getAmount()));
			i++;
		}
		
		ProductAmount[] pas = currentData.string2ProductAmount();
		int j =0;
		for (ProductAmount productAmount : pas) {
			
//			cpProducts[i].setText(unitAmount.getName());
			cpProductsAmount[j].setText(String.valueOf(productAmount.getAmount()));
			j++;
		}
		
		resetTextStatus(!"元件已发放".equals(currentData.getStatus()));
	}

	private void resetTextStatus(boolean editable) {
//		cpUser.setEditable(editable);
		cpUser.setEnabled(editable);
//		cpStatus.setEditable(editable);
		cpStatus.setEnabled(editable);
		cpMemo.setEditable(editable);
		 
		 for (JCNumberField amount : cpProductsAmount) {
			 amount.setEditable(editable);
		 }
		 
		 for (JCNumberField amount : cpReturnMaterialsAmount) {
			 amount.setEditable(editable);
		 }
	}

	private void resetButtonStatus(boolean modifying) {
		this.modifying = modifying;
		btnSubmit.setVisible(modifying);
		btnCancel.setVisible(modifying);
		btnInsert.setVisible(!modifying);
		btnModify.setVisible(!modifying);
		btnDelete.setVisible(!modifying);
	}

	private void select(MouseEvent e) {
		int row = table.rowAtPoint(e.getPoint());

		if (row >= 0 && SwingUtilities.isRightMouseButton(e)) {
			table.getSelectionModel().setSelectionInterval(row, row);
		} else if (row < 0 && !SwingUtilities.isMiddleMouseButton(e)) {
			if (selectedIndex >= 0) {
				table.clearSelection();
			} else {
				resetDetailValues();
			}
		}
	}

	private void showPopupMenu(MouseEvent e) {
		if (popup != null && SwingUtilities.isRightMouseButton(e)) {
			popup.show((Component) e.getSource(), e.getX(), e.getY());
		}
	}

	private void whenSelectionChanged(ListSelectionEvent e) {
		currentData = table.getSelectedRow() < 0 ? null : model.getSelectedRowData();
		boolean selectedEmpty = (selectedIndex = table.getSelectedRow()) < 0;
		modifyAction.setEnabled(!selectedEmpty);
		deleteAction.setEnabled(!selectedEmpty);
		resetDetailValues();
	}

	protected void resetRowValues(ProductOut productOut) {
		productOut.setUser(cpUser.getSelectedItem().toString());
		productOut.setStatus(cpStatus.getSelectedItem().toString());
		productOut.setMemo(cpMemo.getEditor().getText());
		productOut.setCreated(new Timestamp(System.currentTimeMillis()));
		productOut.setProducts(prepareProducts());
		productOut.setReturnUnits(prepareReturnUnits());
		
	}
	
	private String prepareReturnUnits() {
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < ecReturnMAmount.length; i++) {
			JCLabel label = null;
			JCNumberField amount = null;
			if(ecReturnMAmount[i].getComponent(0) instanceof JCLabel){
				label = (JCLabel)ecReturnMAmount[i].getComponent(0);
			} else {
				amount = (JCNumberField)ecReturnMAmount[i].getComponent(0);
			}

			if(ecReturnMAmount[i].getComponent(1) instanceof JCLabel){
				label = (JCLabel)ecReturnMAmount[i].getComponent(1);
			} else {
				amount = (JCNumberField)ecReturnMAmount[i].getComponent(1);
			}
			
			sb.append(label.getText());
			
			if(amount.getText() == null || "".equals(amount.getText().trim())){
				sb.append("0").append("|");
			} else {
				sb.append(amount.getText()).append("|");
			}
		}
		
	
		return sb.toString().substring(0, sb.length() -1);
	}

	private String prepareProducts() {
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < ecPAmount.length; i++) {
			JCLabel label = null;
			JCNumberField amount = null;
			if(ecPAmount[i].getComponent(0) instanceof JCLabel){
				label = (JCLabel)ecPAmount[i].getComponent(0);
			} else {
				amount = (JCNumberField)ecPAmount[i].getComponent(0);
			}

			if(ecPAmount[i].getComponent(1) instanceof JCLabel){
				label = (JCLabel)ecPAmount[i].getComponent(1);
			} else {
				amount = (JCNumberField)ecPAmount[i].getComponent(1);
			}
			
			sb.append(label.getText());
			
			if(amount.getText() == null || "".equals(amount.getText().trim())){
				sb.append("0").append("|");
			} else {
				sb.append(amount.getText()).append("|");
			}
		}
		
	
		return sb.toString().substring(0, sb.length() -1);
	}

	public void cancel() {
		btnSubmit.setActionCommand(null);
		resetDetailValues();
	}

	protected boolean checkInput() {
		return true;
	}

	protected boolean checkFilter(User data) {
		return true;
	}

	public void submit() {
		if (!btnSubmit.isVisible() || !checkInput()) {
			return;
		}

		String cmd = btnSubmit.getActionCommand();
		boolean insert = true;
		ProductOut c = null; 
		
		if (CMD_INSERT.equals(cmd)) {
			c = new ProductOut();
			
		} else if (CMD_MODIFY.equals(cmd)) {
			c = currentData;
			insert = false;
		}
		
		if (checkNull(insert)) {

			resetRowValues(c);

			if (insert) {
				if (isStoreEnough(c)) {
					productOutDao.add(c);

					model.insertRowData(c);
					int row = model.convertRowIndexesToView(model.getRowCount() - 1)[0];
					table.getSelectionModel().setSelectionInterval(row, row);
					
					resetButtonStatus(false);
					resetTextStatus(false);
					btnSubmit.setActionCommand(null);
				}

			} else {
				if("新建".equals(cpStatus.getSelectedItem())){
					if (isStoreEnough(c)) {
						productOutDao.update(c);

						model.delRowData(c);
						model.insertRowData(c);
						int row = model.convertRowIndexesToView(model.getRowCount() - 1)[0];
						table.getSelectionModel().setSelectionInterval(row, row);
						
						resetButtonStatus(false);
						resetTextStatus(false);
						btnSubmit.setActionCommand(null);
					}
				} else {
					if (isStoreEnough(c)) {
						productOutDao.update(c);
						ProductOut productOut = productOutDao.findByPK(c.getId());

						if ("元件已发放".equals(c.getStatus())) {
							// update store
							updateStore(c);
							// update out check
							updateStoreCheck(c);
							JCMessageBox.createInformationMessageBox(keeper.getMainFrame(), "元件发放成功", "元件发放成功").open();
						} else {
							JCMessageBox.createInformationMessageBox(keeper.getMainFrame(), "元件发放失败", "请改操作状态为已发放").open();
						}

						// doSomething
						model.refreshRowOnView(selectedIndex);
						fillValues();

						resetButtonStatus(false);
						resetTextStatus(false);
						btnSubmit.setActionCommand(null);
						
						keeper.refreshStatus();
					}
				}

			}


		}

	}

	private boolean checkNull(boolean insert) {
		if (cpUser.getSelectedItem() == null || cpStatus.getSelectedItem() == null ) {

			JCMessageBox.createErrorMessageBox(keeper.getMainFrame(), "必填项为空", "请输入所有必填项").open();

			return false;
		}
		return true;
	}

	private boolean isStoreEnough(ProductOut c2) {
		ProductAmount[] pas = c2.string2ProductAmount();
		UnitAmount[] needs = new UnitAmount[MaterialUtils.getInstance().getAll().size()];
		
		for (int i = 0; i < needs.length; i++) {
			UnitAmount ua = new UnitAmount();
			ua.setAmount(0);
			needs[i] = ua;
		}
		
		for (ProductAmount productAmount : pas) {
			Composite c = compositeDAO.findByPK(productAmount.getName());
			if (c != null) {
				UnitAmount[] uas = c.string2UnitAmount();
				for (int j = 0; j < uas.length; j++) {
					UnitAmount ua = new UnitAmount();
					ua.setName(uas[j].getName());
					ua.setAmount(uas[j].getAmount() * productAmount.getAmount() + needs[j].getAmount());
					needs[j] = ua;
				}
			}
		}

		boolean enough = true;
		for (UnitAmount unitAmount : needs) {
			MaterialStore ms = storeDAO.findByPK(unitAmount.getName());
			if (ms != null) {
				if (ms.getAmount() < unitAmount.getAmount()) {
					enough = false;
					break;
				}
			} else {
				enough = false;
				break;
			}
			
		}
		if (!enough) {
			JCMessageBox.createErrorMessageBox(keeper.getMainFrame(), "元件数量不足", "元件数量不足,请核对!").open();
		}
		return enough;
	}

	private void updateStore(ProductOut p) {
		returnBack(p);
		buildProducts(p);
	}

	private void updateStoreCheck(ProductOut p) {
		ProductOutCheck check = new ProductOutCheck();
		check.setOutId(p.getId());
		check.setShouldProducts(p.getProducts());
		check.setNeedProducts(p.getProducts());
		updateRealProducts(check);
		check.setStatus(OutCheckStatus.NONE.getMessage());
		check.setUser(p.getUser());
		check.setMemo("");
		check.setCreated(p.getCreated());
		productOutCheckDAO.add(check);
	}
	
	private void updateRealProducts(ProductOutCheck poc) {
		ProductAmount[] pas = poc.string2ProductAmount(poc.getShouldProducts());
		for (ProductAmount productAmount : pas) {
			productAmount.setAmount(0);
		}
		
		poc.setRealProducts(poc.productAmount2String(pas));
		
	}

	private void buildProducts(ProductOut p) {
		ProductAmount[] pas = p.string2ProductAmount();

		for (ProductAmount productAmount : pas) {
			if (productAmount.getAmount() != 0) {
				UnitAmount[] uas = compositeDAO.findByPK(productAmount.getName()).string2UnitAmount();
				for (UnitAmount unitAmount : uas) {
					if (unitAmount.getAmount() != 0) {
						MaterialStore store = storeDAO.findByPK(unitAmount.getName());

						store.setAmount(store.getAmount() - unitAmount.getAmount()*productAmount.getAmount());

						storeDAO.updateStore(store);

						MStoreLog log = new MStoreLog();
						log.setAction(StoreChangeActions.OUT.getMessage());
						log.setAmount(0 - unitAmount.getAmount() * productAmount.getAmount());
						log.setCreated(new Timestamp(System.currentTimeMillis()));
						log.setMaterial(unitAmount.getName());
						log.setMemo(p.getMemo() + "-出库流水为:" + p.getId());
						log.setUser(p.getUser());
						log.setOperator(currentUser.getName());
						mStoreLogDAO.add(log);
					}
				}
			}

		}
	}

	private void returnBack(ProductOut p) {
		UnitAmount[] uas = p.string2UnitAmount();

		for (UnitAmount unitAmount : uas) {
			if (unitAmount.getAmount() != 0) {
				MaterialStore store = storeDAO.findByPK(unitAmount.getName());

				store.setAmount(store.getAmount() - unitAmount.getAmount());

				storeDAO.updateStore(store);

				MStoreLog log = new MStoreLog();
				log.setAction(StoreChangeActions.RETURN.getMessage());
				log.setAmount(0 - unitAmount.getAmount());
				log.setCreated(new Timestamp(System.currentTimeMillis()));
				log.setMaterial(unitAmount.getName());
				log.setMemo(p.getMemo() + "|, 出库流水为:" + p.getId());
				log.setUser(p.getUser());
				log.setOperator(currentUser.getName());
				mStoreLogDAO.add(log);
			}
		}
	}

	public void insertOrModify(boolean insert) {
		if (modifying) {
			cancel();
		}

		btnSubmit.setActionCommand(insert ? CMD_INSERT : CMD_MODIFY);

		resetTextStatus(true);
		resetButtonStatus(true);

		if (insert) {
			clearValues();
			cpUser.requestFocus();
			cpStatus.setSelectedItem("新建");
			cpStatus.setEnabled(false);
		} 
	}

	public void delete() {
		String message = "\u786E\u5B9A\u8981\u5220\u9664\u8BE5\u8BB0\u5F55\u5417\uFF1F";
		JCMessageBox box = JCMessageBox.createQuestionMessageBox(keeper.getMainFrame(), "\u5220\u9664", message);

		if (box.open() == JCMessageBox.YES_OPTION) {
			productOutDao.delete(currentData);
			model.delRowOnViewAt(selectedIndex);
		}
	}

	public List<Composite> getAllData() {
//		return data;
		return new ArrayList<Composite>();
	}

	@Override
	public String getType() {
		return "成品类型管理";
	};


	@Override
	public void refresh() {
		load();
		this.removeAll();
		
		initActions();
		initUI();
		keeper.refreshStatus();
	}
}
